<?php
/**
 * Author: xx.com
 */ 
namespace Api\Controller;
use Think\Controller;
use Home\Logic\GoodsLogic;
class IndexController extends BaseController {
    public function index(){
        $this->display();
    }
 
    /*
     * 获取首页数据
     */
    public function home(){
        //获取轮播图
        //$data = M('ad')->where('pid = 2')->field(array('ad_link','ad_name','ad_code'))->cache(true,LNSHOP_CACHE_TIME)->select();
        $data = M('ad')->where('pid = 2')->field(array('ad_link','ad_name','ad_code'))->select();
        //广告地址转换
        foreach($data as $k=>$v)
        {
            // if(!strstr($v['ad_link'],'http'))
            //     $data[$k]['ad_link'] = SITE_URL.$v['ad_link'];
            
            $data[$k]['ad_code'] = parseMediaUrl($v['ad_code']);
        }
        //获取大分类
        //$category_arr = M('goods_category')->where('parent_id=0')->field('id,name')->limit(3)->cache(false,LNSHOP_CACHE_TIME)->select();
        $category_arr = M('goods_category')->where('parent_id=0')->field('id,name')->limit(3)->select();
        $result = array();
        foreach($category_arr as $c){
            $cat_arr = getCatGrandson($c['id']);
            //获取商品
            //$sql = "select goods_name,goods_id,original_img,shop_price from __PREFIX__goods where  cat_id in (".implode(',',$cat_arr).") limit 4";
            //$goods = M()->query($sql);
            if($cat_arr)
                $cat_id = implode (',', $cat_arr);
            //$goodsList = M('goods')->where("cat_id in($cat_id)")->limit(4)->cache(false,LNSHOP_CACHE_TIME)->getField("goods_id,goods_name,original_img,shop_price");
            $goodsList = M('goods')->where("cat_id in($cat_id)")->limit(4)->order('sort desc,on_time desc')->getField("goods_id,goods_name,original_img,shop_price");
            foreach($goodsList as $k => $v){
                $v['original_img'] = parseMediaUrl($v['original_img']);
                $c['goods_list'][] = $v;
            }            
            $result[] = $c;
        }

        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('goods'=>$result,'ad'=>$data))));
    }
	
	/*
	 * 获取首页分类数据
	 */
	public function homecategory(){
	    //获取轮播图
	    //$data = M('ad')->where('pid = 2')->field(array('ad_link','ad_name','ad_code'))->cache(true,LNSHOP_CACHE_TIME)->select();
	    $data = M('ad')->where('pid = 2')->field(array('ad_link','ad_name','ad_code'))->select();
	    //广告地址转换
	    foreach($data as $k=>$v)
	    {
	        // if(!strstr($v['ad_link'],'http'))
	        //     $data[$k]['ad_link'] = SITE_URL.$v['ad_link'];
	        
	        $data[$k]['ad_code'] = parseMediaUrl($v['ad_code']);
	    }
	    //获取大分类
	    $category_arr = M('goods_category')->field('id,mobile_name,image')->order('sort_order desc')
            ->where('parent_id=0 and is_show = 1 and is_hot = 1')->limit(10)->cache(false,LNSHOP_CACHE_TIME)->select();
	    // $category_arr = M('goods_category')->where('parent_id=0 and is_hot = 1 and is_show = 1')->field('id,mobile_name,image')->order('sort_order desc')->limit(9)->select();
	    $result = array();
	    foreach($category_arr as $c){
	        $c['image'] = parseMediaUrl($c['image']);      
	        $result[] = $c;
	    }
	
	    exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('category'=>$result,'ad'=>$data))));
	}

   /*
     * 获取首页轮播图
     */
    public function adlist(){
        //获取轮播图
        $data = M('ad')->where('pid = 2')->field(array('ad_link','ad_name','ad_code'))->cache(true,LNSHOP_CACHE_TIME)->select();
        //广告地址转换
        foreach($data as $k=>$v){
            // if(!strstr($v['ad_link'],'http'))
            //     $data[$k]['ad_link'] = SITE_URL.$v['ad_link'];
            $data[$k]['ad_code'] = parseMediaUrl($v['ad_code']);

        }

        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$data)));
    }


    /*
     * 获取首页活动图片+文字
     */
     public function activList(){
        //获取轮播图
        $data = M('ad')->where('pid = 1')->field(array('ad_name','ad_code'))->cache(true,LNSHOP_CACHE_TIME)->select();
        //广告地址转换
        foreach($data as $k=>$v){
            $data[$k]['ad_code'] = parseMediaUrl($v['ad_code']);
        }

        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$data)));
    }
    

    /**
     * 获取首页数据
     */
    public function homePage(){
        $header = $this->get_all_header();
        // $promotion_goods = D('Goods')->getPromotionGoods();
        // $high_quality_goods = D('Goods')->getHighQualityGoods();
        // $new_goods = D('Goods')->getNewGoods();
        $adv =  D('Goods')->getHomeAdv();//轮播
        $activ = D('Goods')->getHomeActiv();//活动
        $zhuan = D('Goods')->getHomeZhuan();//看广告赚钱
        $seckill = D('Goods')->getSecKill();//限时秒杀
        $hot_goods = D('Goods')->getHotGood();//热销商品
        $qiang = D('Goods')->getHomeQiang();//抢位
        $json = array(
            'status'=>1,
            'msg'=>'获取成功',
            'result'=>array(
                // 'promotion_goods'=>$promotion_goods,
                // 'high_quality_goods'=>$high_quality_goods,
                // 'new_goods'=>$new_goods,
                'hot_goods'=>$hot_goods,
                'ad'=>$adv,
                'activ'=>$activ,
                'zhuan'=>$zhuan,
                'qiang'=>$qiang,
                'seckill'=>$seckill
            ),
        );
        exit(json_encode($json));
    }


    //获取热销商品banner
    public function getHotBanner(){
        $where = array();
        $where['g.is_hot'] = 1;
        $where['g.is_on_sale'] = 1;
        $banner = M('goods_category as gc')
                ->field('DISTINCT(gc.id) as id,gc.mobile_name')
                ->join('ln_goods as g on g.cat_id=gc.id')
                ->where($where)
                ->order('g.sort desc,g.on_time desc')
                ->select();
        // foreach ($banner as $key => $value) {
        //     $where = "id=".$value['id'];
        //     $parent_id_path = M('goods_category')->field('parent_id_path')->where($where)->find();
        //     $parent_id = explode('_',$parent_id_path['parent_id_path']);
        //     $parent_id = $parent_id[1];
        //     unset($where);
        //     $where = "id=".$parent_id ;
        //     $mobile_name = M('goods_category')->field('mobile_name')->where($where)->find();
        //     $banner[$key]['mobile_name'] = $mobile_name['mobile_name'];
        // }
         exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$banner)));
    }


    public function getHotGood()
    {
        $id = I('id');
        $page = I('p') ? I('p') : I('page',1);
        $goods_where = array('is_on_sale' => 1,'prom_id'=>0,'prom_type'=>0);
        if( $id )
        {
            $goods_where['cat_id'] = $id;
        }
        $orderBy = array('sort' => 'desc');
        $new_goods = M('goods')
            ->field('goods_id,goods_name,shop_price,market_price,original_img')
            ->where($goods_where)
            ->page($page,20)
            ->order($orderBy)
            ->select();
        foreach($new_goods as $k => &$v)
        {
            $v['original_img'] = parseMediaUrl( $v['original_img'] );
        }
        $this->returnInfo('1','获取成功',$new_goods);
    }


    //获取品牌清仓banner
    public function getClearBanner(){
        $where = [];
        $where['g.is_on_sale'] = 1;
        $where['g.prom_type'] = 3;
        $where['pg.is_close'] = 0;
        $where['pg.start_time'] = ['lt',time()-1];
        $where['pg.end_time'] = ['gt',time()+10];
        // 原代码的神逻辑我已经无语
        $banner = M('goods_category as gc')
                ->field('DISTINCT(gc.id),gc.mobile_name')
                ->join('ln_goods as g on g.cat_id=gc.id')
                ->join('ln_prom_goods as pg on pg.id=g.prom_id')
                ->where($where)
                ->fetchSql(0)
                ->select();

        foreach ($banner as $key => $value) {
            $where = "id=".$value['id'];
            $parent_id_path = M('goods_category')->field('parent_id_path')->where($where)->find();
            $parent_id = explode('_',$parent_id_path['parent_id_path']);
            $parent_id = $parent_id[1];
            unset($where);
            $where = "id=".$parent_id ;
            $mobile_name = M('goods_category')->field('mobile_name')->where($where)->find();
            $banner[$key]['mobile_name'] = $mobile_name['mobile_name'];
        }


         exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$banner)));
    }
	
	/**
	 * 获取清仓商品列表
	 */
    public function getClearList()
    {
        $id=I('id')?I('id'):1;
        if ($id) {
            $now = time();
            // $wheres['g.cat_id'] = $id;
            $wheres['g.prom_type'] = 3;
            $wheres['g.is_on_sale'] = 1;
            $wheres['pg.is_close'] = 0;
            $wheres['pg.start_time'] = ['lt',time()-1];
            $wheres['pg.end_time'] = ['gt',time()+10]; 
            $orderBy = array('sort' => 'desc');
            $goods = M('goods as g')
                ->field('g.goods_id,g.goods_name,g.market_price,g.goods_remark,g.shop_price,g.original_img,pg.type as prominfo_type,pg.expression as prominfo_expression')
                // ->join("ln_goods_category as gc on gc.id=$id")
                ->join('ln_prom_goods as pg on pg.id=g.prom_id')
                ->where($wheres)
                ->order($orderBy)
                ->select();

            foreach ($goods as $key => &$value) 
            {
                $value['original_img'] = parseMediaUrl($value['original_img']);

                if($value['prominfo_type'] == 0){
                    $price = $value['shop_price']*$value['prominfo_expression']/100;//打折优惠
                }elseif($value['prominfo_type'] == 1){
                    $price = $value['shop_price']-$value['prominfo_expression'];//减价优惠
                    $value['shop_price'] < 0 ? 0 : $value['shop_price']; 
                }
                if( $price )
                {
                    $value['shop_price'] = $price;
                }
				$value['gallery'] = M('goods_images')->field('image_url')->where(array('goods_id'=>$value['goods_id']))->select();
				foreach($value['gallery'] as $item => $val){
				   $value['gallery'][$item]['image_url'] = parseMediaUrl($value['gallery'][$item]['image_url']);
				}
				$value['gallery']?$value['gallery']:[];

                // foreach ($new_goods as $key1 => &$value1) 
                // {
                //     $value1['original_img'] = parseMediaUrl($value1['original_img']);
                //     $where = "is_close=0 and id=".$value['prom_id'] ;
                //     $prominfo = M('prom_goods')->where($where)->find(); //查询优惠活动
                //     if (!empty($prominfo)) {
                //         if($prominfo['type'] == 0){
                //             $price = $value['shop_price']*$prominfo['expression']/100;//打折优惠
                //         }elseif($prominfo['type'] == 1){
                //             $price = $value['shop_price']-$prominfo['expression'];//减价优惠
                //             $value['shop_price'] < 0 ? 0 : $value['shop_price']; 
                //         }
                //         if( $price )
                //         {
                //             $value1['shop_price'] = $price;
                //         }
                //     }             
                // }
                // 上面的这么写就不用下面的了
                // $shop_price[] = array('shop_price'=>strval($value1['shop_price']."."."00"));
                // foreach ($shop_price as $key2 => $value2)
                // {
                //     $new_goods[$key]['shop_price'] = $value2['shop_price'];
                // }
            }
        }else{
            exit(json_encode(array('status'=>1,'msg'=>'暂无品牌清仓商品','result'=>[])));
        }
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$goods)));
    }



    /*
     * 获取app启动页
     */
    public function adStart(){
        //获取轮播图
        $data = M('ad')->where('pid = 51317')->order('orderby desc')->select();  
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$data)));   
        }  


    /**
     * 猜你喜欢
     */

    public function favourite()
    {
        $p = I('p',1);
        $goods_where = array('is_recommend'=>1,'is_on_sale'=>1,);
        $favourite_goods = M('goods')->field('goods_id,goods_name,shop_price,market_price,original_img')->where($goods_where)->order('sort desc,on_time desc')->page($p,10)->select();
        foreach($favourite_goods as $k => &$v)
        {
            $v['original_img'] = parseMediaUrl($v['original_img']);
        }
        $json = array(
            'status'=>1,
            'msg'=>'获取成功',
            'result'=>array(
                'favourite_goods'=>$favourite_goods,
            ),
        );
        exit(json_encode($json));
    }


    ///首页搜索
    public function seach(){

    }
    
    /**
     * 获取服务器配置
     */
    public function getConfig()
    {
        $config_arr = M('config')->select();
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$config_arr)));
    }
    /**
     * 获取插件信息
     */
    public function getPluginConfig()
    {
        $data = M('plugin')->where("type='payment' OR type='login'")->select();
        $arr = array();
        foreach($data as $k=>$v){
            unset( $data[$k]['config']);
            unset( $data[$k]['config']);

            $data[$k]['config_value'] = unserialize($v['config_value']);
            if($data[$k]['type'] == 'payment'){
                $arr['payment'][] =  $data[$k];
            }
            if($data[$k]['type'] == 'login'){
                $arr['login'][] =  $data[$k];
            }
        }
        exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>$arr ? $arr : '')));
    }

    /**
     * 是否开启app自动更新
     */
    public function getAppAutoupdate(){
        $autoupdate = M('config')->where(array('name'=>'app_autoupdate'))->find();
        if($autoupdate){
            $autoupdate_info = intval($autoupdate['value']);
        }else{
            $autoupdate_info = 0;
        }

        $this->ajaxReturn(array('status'=>1,'msg'=>'获取成功','result'=>$autoupdate_info));
    }

    public function home_cate_goods(){

        $category_arr = M('goods_category')->field('id,mobile_name,home_image as image')->order('sort_order desc')
            ->where('parent_id=0 and is_show = 1 and is_hot = 1')->limit(10)->cache(false,LNSHOP_CACHE_TIME)->select();
        // $category_arr = M('goods_category')->where('parent_id=0 and is_hot = 1 and is_show = 1')->field('id,mobile_name,image')->order('sort_order desc')->limit(9)->select();
        $result = array();
        $goodsModel = M('goods');
        foreach($category_arr as $c){
            $c['image'] = parseMediaUrl($c['image']);

            $cat_id_arr = getCatGrandson ($c['id']);
            $cids = implode(',', $cat_id_arr);
            $goodsList = $goodsModel->field('goods_id, goods_name, market_price, shop_price, original_img, store_count')
                ->where(array('is_on_sale'=>1, 'cat_id'=>array('in', $cids),'is_recommend'=>1))->order('`sort` DESC, on_time DESC')
                ->select();
            foreach($goodsList as &$val){
                $val['original_img'] = parseMediaUrl($val['original_img']);
            }
            $c['goods_list'] = $goodsList;
            $result[] = $c;
        }
        $this->returnInfo(1, '获取成功', $result);
        //exit(json_encode(array('status'=>1,'msg'=>'获取成功','result'=>array('category'=>$result,'ad'=>$data))));
    }
}